<template>
	<!-- 自定义导航栏 -->
	<!-- <CustomNavBar title="伙伴圈,在这里可以看伙伴发的帖子" /> -->
	<view v-for="(post, index) in postList" :key="post.id" class="post-card">
		<up-card :title="post.username" :thumb="post.avatarUrl" thumb-size="60" thumb-radius="30" :thumb-border="true"
			:foot-border-top="false" :head-border-bottom='false'>
			<template #body>
				<!-- 描述部分 -->
				<view class="post-content" @click="doPostInfo(post.id)">
					{{ post.content }}
				</view>
			</template>
			<template #foot>
				<view class="button-container">
					<up-button iconColor="#909399" @click="preAddComment(post.id)" icon='chat-fill'
						class="action-button">评论</up-button>
					<up-button :iconColor="post.thumb ? '#ee0a24' : '#909399'" @click="doThumb(index,post.id)"
						icon='thumb-up-fill' class="action-button">{{post.thumbNum}}</up-button>
					<up-button v-if="post.userId === currentUser?.id" iconColor="#ee0a24" @click="doDeletePost(post.id)"
						class="action-button">删除</up-button>
				</view>
			</template>
		</up-card>

		<!-- 评论列表 -->
		<view v-for="comment in post.postCommentList" :key="comment.id" class="comment-item">
			<up-cell :title="comment.username" :icon="comment.avatarUrl" :label="comment.content" :is-link="false" />
		</view>

		<!-- 分割线 -->
		<up-divider lineColor="#1989fa" class="divider" />
	</view>

	<!-- 空状态组件 -->
	<up-empty v-if="!postList || postList.length < 1" description="无符合的帖子" />

	<up-popup :show="show" mode="bottom" @close="doAddCommentCancel">
		<up-form @submit.prevent="doAddComment">
			<up-form-item borderBottom labelWidth='120rpx' style="padding-left: 30rpx;">
				<up-textarea v-model="comment" placeholder="请输入评论" count :maxlength='200'></up-textarea>
			</up-form-item>

			<view style="margin: 16px;">
				<up-button type="primary" @click="doAddComment">
					发送
				</up-button>
			</view>
		</up-form>
	</up-popup>
	<view class='iconBox'>
		<up-icon name="plus" color="#fff" size="28" @click="doPostAdd"></up-icon>
	</view>
</template>

<script setup lang="ts">
	import CustomNavBar from '@/components/CustomNavBar.vue';
	import { onMounted, ref, watchEffect } from 'vue';
	import myAxios from '@/plugins/myAxios'; // 请确保路径正确
	import type { postType } from '@/models/post';
	import { getCurrentUser } from '@/services/user';
	import { onShow } from '@dcloudio/uni-app';

	// 当前用户信息
	const currentUser = ref('');
	// 评论内容
	const comment = ref('');
	// 帖子列表，包含初始的假数据
	const postList = ref<postType[]>([]);

	// 控制评论弹窗的显示
	const show = ref(false);
	// 当前正在添加评论的帖子 ID
	const addCommentPost = ref<number>(0);
	// 当前页码
	const currentPage = ref<number>(1);

	/**
	 * 删除帖子
	 */
	const doDeletePost = async (id : number) => {
		try {
			const res = await myAxios.post("/post/delete", { id });
			if (res?.code === 0) {
				uni.showToast({ title: '删除成功', icon: 'success' });
				// 更新帖子列表，移除已删除的帖子
				postList.value = postList.value.filter(post => post.id !== id);
			} else {
				uni.showToast({ title: '删除失败' + (res.description ? `,${res.description}` : ''), icon: 'none' });
			}
		} catch (error) {
			uni.showToast({ title: '网络错误，删除失败', icon: 'none' });
		}
	};

	/**
	 * 获取帖子的列表
	 */
	const listPost = async () => {
		try {
			const res = await myAxios.get("/post/list", {
				pageNum: currentPage.value,
				pageSize: 20,
			});
			if (res?.code === 0 && res.data) {
				postList.value = res.data;
			} else {
				uni.showToast({ title: '加载帖子失败' + (res.description ? `,${res.description}` : ''), icon: 'none' });
			}
		} catch (error) {
			uni.showToast({ title: '网络错误，加载失败', icon: 'none' });
		}
	};

	/**
	 * 添加帖子
	 */
	const doPostAdd = () => {
		uni.navigateTo({
			url: '/pages/forum/add' // 请确保路径正确
		});
	};

	/**
	 * 预先添加评论，显示评论弹窗
	 */
	const preAddComment = (postId : number) => {
		show.value = true;
		addCommentPost.value = postId;
	};

	/**
	 * 给帖子评论
	 */
	const doAddComment = async () => {
		if (!comment.value.trim()) {
			uni.showToast({ title: '评论内容不能为空', icon: 'none' });
			return;
		}
		try {
			const res = await myAxios.post("/post/addComment", {
				content: comment.value,
				postId: addCommentPost.value,
			});
			if (res?.code === 0) {
				uni.showToast({ title: '评论成功', icon: 'success' });
				doAddCommentCancel();
				// 可选：重新加载帖子列表或手动更新评论列表
				// listPost();
				await listPost();
			} else {
				uni.showToast({ title: '评论失败' + (res.description ? `,${res.description}` : ''), icon: 'none' });
			}
		} catch (error) {
			uni.showToast({ title: '网络错误，评论失败', icon: 'none' });
		}
	};

	/**
	 * 关闭评论弹窗
	 */
	const doAddCommentCancel = () => {
		comment.value = '';
		show.value = false;
	};

	/**
	 * 点赞
	 */
	const doThumb = async (index : number, postId : number) => {
		try {
			const res = await myAxios.post("/post_thumb/", { postId });
			if (res?.code === 0) {
				// 返回为1表示点赞，返回为-1表示取消点赞
				if (res.data === 1) {
					postList.value[index].thumbNum += 1;
				} else {
					postList.value[index].thumbNum -= 1;
				}
				postList.value[index].thumb = !postList.value[index].thumb;
			} else {
				uni.showToast({ title: '点赞失败' + (res.description ? `,${res.description}` : ''), icon: 'none' });
			}
		} catch (error) {
			uni.showToast({ title: '网络错误，点赞失败', icon: 'none' });
		}
	};

	/**
	 * 跳转帖子详情
	 */
	const doPostInfo = (id : number) => {
		uni.navigateTo({
			url: `/pages/forum/detail?id=${id}` // 请确保路径正确
		});
	};

	/**
	 * 初始化函数，挂载时执行
	 */
	onMounted(async () => {
		await listPost();
		const user = await getCurrentUser();
		currentUser.value = user || {};
	});

	/**
	 * 监听 addCommentPost 的变化（可选）
	 */
	watchEffect(() => {
		// 目前没有需要响应的逻辑，可以删除或保留
	});

	onShow(async () => {
		await listPost();
	})
</script>


<style lang='scss' scoped>
	.post-card {
		margin-bottom: 16px;
		/* 增加帖子之间的间距 */
	}

	.button-container {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		width: 100%;
	}

	.action-button {
		margin-left: 10rpx;
		/* 按钮之间的间距 */
	}

	.comment-item {
		margin: 8px 0;
		/* 评论之间的间距 */
	}

	.divider {
		margin: 16px 0;
		/* 分割线的上下间距 */
	}

	.iconBox {
		position: fixed;
		bottom: 20px;
		right: 20px;
		z-index: 999;
		width: 60px;
		height: 60px;
		display: flex;
		justify-content: center;
		align-items: center;
		background-color: #49a1ff;
		border-radius: 50%;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
		border: 1px solid #e5e5e5;
	}

	.iconBox:active {
		transform: scale(0.95);
		transition: transform 0.1s ease-in-out;
	}
</style>